﻿using System.Linq;
using Tools.Domain.Specifications;
using Webshop20.Application.Queries.Messages;
using Webshop20.Domain.Catalog.Repositories.Contracts;
using Webshop20.Domain.Common.Factories.Contracts;
using Webshop20.Domain.Shared.Products.Core;

namespace Webshop20.Application.Queries.Services
{
    public interface IGetProductsBySpecificationService: IService{}

    public class GetProductsBySpecificationService : ServiceBase, IGetProductsBySpecificationService
    {
        private readonly IProductRepository productRepository;
        private readonly ISpecificationFactory<Product> specificationFactory;

        public GetProductsBySpecificationService(IProductRepository productRepository,
                                                 ISpecificationFactory<Product> specificationFactory)
        {
            this.productRepository = productRepository;
            this.specificationFactory = specificationFactory;
        }

        public override ISystemMessage Handle(ISystemMessage request)
        {
            var getProductsBySpecificationRequest = request as GetProductsBySpecificationRequest;
            ISpecification<Product> productSpecifictaion =
                specificationFactory.CreateSpecification(getProductsBySpecificationRequest.SpecificationKey);
            return new GetProductsBySPecificationResponse(
                productRepository
                    .FindBySpecification(productSpecifictaion)
                    .AsEnumerable()
                );
        }
    }
}